package xyz.herz.aic.controller;

import lombok.extern.slf4j.Slf4j;
import org.noear.solon.annotation.*;
import org.noear.solon.core.handle.Result;
import org.noear.wood.DbContext;
import org.noear.wood.annotation.Db;

import java.util.List;
import java.util.Map;

/**
 * 数据库测试
 */
@Controller
@Mapping("/db")
@Slf4j
public class DBCtl {

    @Db
    DbContext db;


    /**
     * 新增
     *
     * @param tableName 表名
     * @param record    插入对象
     * @return
     * @throws Exception
     */
    @Post
    @Mapping("/insert/{tableName}")
    public Result insert(@Path String tableName, @Body Map record) throws Exception {
        return Result.succeed(db.table(tableName)
                .setMap(record)
                .insert());
    }

    /**
     * 查询
     *
     * @param tableName 表名
     * @param start     分页页码
     * @param size      分页条数
     * @return
     * @throws Exception
     */
    @Get
    @Mapping("/select/{tableName}")
    public Result<List<Map<String, Object>>> select(@Path String tableName, @Param Integer start, @Param Integer size) throws Exception {
        return Result.succeed(db.table(tableName)
                .limit(start, size)
                .selectMapList("*"));
    }


    /**
     * 更新
     *
     * @param tableName 表名
     * @param record    插入对象
     * @return
     * @throws Exception
     */
    @Post
    @Mapping("/update/{tableName}")
    public Result<Integer> update(@Path String tableName, @Param Integer id, @Body Map record) throws Exception {
        return Result.succeed(db.table(tableName)
                .setMap(record)
                .whereEq("ID", id)
                .update());
    }


    /**
     * 更新
     *
     * @param tableName 表名
     * @param id        主键值
     * @return
     * @throws Exception
     */
    @Delete
    @Mapping("/delete/{tableName}")
    public Result<Integer> userList(@Path String tableName, @Param Integer id) throws Exception {
        return Result.succeed(db.table(tableName)
                .whereEq("ID", id)
                .delete());
    }
}


